package com.example.xxpk.service.useroutifts;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.xxpk.bo.OutfitInfo;
import com.example.xxpk.mapper.OutiftsMapper;
import com.example.xxpk.mapper.OutiftsTrialRecordMapper;
import com.example.xxpk.mapper.UserOutiftsMapper;
import com.example.xxpk.pojo.Outifts;
import com.example.xxpk.pojo.OutiftsTrialRecord;
import com.example.xxpk.pojo.UserOutifts;
import com.example.xxpk.pojo.Users;
import com.example.xxpk.service.users.IUsersService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangguihong
 * @since 2025-02-13
 */
@Service
@RequiredArgsConstructor
public class UserOutiftsServiceImpl extends ServiceImpl<UserOutiftsMapper, UserOutifts> implements IUserOutiftsService {

    private final IUsersService usersService;

    private final OutiftsMapper outiftsMapper;

    private final UserOutiftsMapper userOutfitMapper;

    private final OutiftsTrialRecordMapper outfitTrialMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<OutfitInfo> getOutfitInfoByUserIdAndCategory(Integer userId, String category) {
        List<OutfitInfo> outfitInfoList = userOutfitMapper.getOutfitInfoByUserIdAndCategory(userId, category);

        // 标记是否有正在使用的装扮
        boolean hasUsingOutfit = false;
        OutfitInfo defaultOutfit = null;

        // 处理 type 为 3 的情况，默认拥有
        for (OutfitInfo outfitInfo : outfitInfoList) {
            if ("3".equals(outfitInfo.getType())) {
                outfitInfo.setStatus(1);
                if (defaultOutfit == null) {
                    defaultOutfit = outfitInfo;
                }
            }
            if (outfitInfo.getIsUsing() != null && outfitInfo.getIsUsing() == 1) {
                hasUsingOutfit = true;
            }
        }

        // 如果没有正在使用的装扮，默认使用 type 为 3 的装扮
        if (!hasUsingOutfit && defaultOutfit != null) {
            Users user = new Users();
            user.setUserId(userId);
            user.setRoleId(defaultOutfit.getOutiftsId());
            usersService.saveOrUpdate(user);
            defaultOutfit.setIsUsing(1);
        }

        return outfitInfoList;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer canTrialOutfit(Integer userId, Integer outiftsId ) {
        Outifts outifts = outiftsMapper.selectById(outiftsId);
        if ("0".equals(outifts.getIsDisplayed())){
            throw new RuntimeException("试用失败，该装扮未上线");
        }
        QueryWrapper<OutiftsTrialRecord> trialQuery = new QueryWrapper<>();
        trialQuery.eq("user_id", userId)
                .eq("outifts_id", outiftsId)
                .ge("create_time", LocalDateTime.now().truncatedTo(ChronoUnit.DAYS));
        List<OutiftsTrialRecord> trials = outfitTrialMapper.selectList(trialQuery);

        if (trials.size() >= 3) {
            throw new RuntimeException("今日试用次数已达3次");
        }

        if (!trials.isEmpty()) {
            LocalDateTime lastTrialTime = trials.get(trials.size() - 1).getCreateTime();
            if (ChronoUnit.HOURS.between(lastTrialTime, LocalDateTime.now()) < 1) {
                throw new RuntimeException("试用失败，距离上次试用未超过一小时");
            }
        }

        return outifts.getCategory();
    }

    //将同类别装扮设为0
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unuseOtherOutfits(Integer userId, Integer category) {
        UpdateWrapper<UserOutifts> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId)
                .eq("category", category)
                .set("is_using", 0);
        this.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean useOutfit(Integer userId, Integer outiftsId) {
        UpdateWrapper<UserOutifts> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId)
                .eq("outifts_id", outiftsId)
                .set("is_using", 1);
        return this.update(updateWrapper);
    }

    @Override
    public boolean isUserOwnOutfit(Integer userId, Integer outiftsId) {
        QueryWrapper<UserOutifts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("outifts_id", outiftsId)
                .eq("status", 1); // 状态为 1 表示已拥有
        return this.count(queryWrapper) > 0;
    }

    //试玩装扮
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordTrialOutfit(Integer userId, Integer outiftsId,Integer category) {

        OutiftsTrialRecord outiftsTrialRecord = new OutiftsTrialRecord();
        outiftsTrialRecord.setUserId(userId);
        outiftsTrialRecord.setOutiftsId(outiftsId);
        outfitTrialMapper.insert(outiftsTrialRecord);

        unuseOtherOutfits(userId,category); //其他装扮设为未使用

        UserOutifts userOutifts = new UserOutifts();
        userOutifts.setUserId(userId);
        userOutifts.setOutiftsId(outiftsId);
        userOutifts.setCategory(category);
        userOutifts.setLevel(1);
        userOutifts.setStatus(2);
        userOutifts.setIsUsing(1);
        // 构造查询条件
        QueryWrapper<UserOutifts> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("outifts_id", outiftsId);

        // 调用 saveOrUpdate 方法
        this.saveOrUpdate(userOutifts, queryWrapper);
        Users user = new Users();
        user.setUserId(userId);
        user.setRoleId(outiftsId);
        usersService.saveOrUpdate(user);
    }

    //试玩结束
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordTrialOutOutfit(Integer userId, Integer outiftsId) {
        Outifts outifts = outiftsMapper.selectById(outiftsId);
        unuseOtherOutfits(userId,outifts.getCategory()); //把当前类别找不到状态都设为0
        //查询该类别默认装扮
        LambdaQueryWrapper<Outifts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Outifts::getCategory,outifts.getCategory())
                    .eq(Outifts::getType,3);
        Outifts outifts1 = outiftsMapper.selectOne(queryWrapper);
        //设置用户为默认装扮
        Users user = new Users();
        user.setUserId(userId);
        user.setRoleId(outifts1.getOutiftsId());
        usersService.saveOrUpdate(user);

        LambdaUpdateWrapper<UserOutifts> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserOutifts::getUserId,userId)
                    .eq(UserOutifts::getOutiftsId,outiftsId)
                    .set(UserOutifts::getLevel,0)
                    .set(UserOutifts::getExperience,0)
                    .set(UserOutifts::getStatus,3)
                    .set(UserOutifts::getIsUsing,0);
        this.update(updateWrapper);

    }

    @Override
    public OutfitInfo getOutfitInfoByUserIdAndOutiftsId(Integer userId, Integer outiftsId) {
        return outiftsMapper.getOutfitInfoByUserIdAndOutiftsId(userId, outiftsId);
    }



}
